package com.skyworthclub.competition.service.impl;

import com.skyworthclub.competition.beans.User;
import com.skyworthclub.competition.repository.UserRedisRepository;
import com.skyworthclub.competition.service.UserRedisCacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @author li
 * @version 1.0
 * @date 2019-07-07 15:40
 **/
@Service
public class UserRedisCacheServiceImpl implements UserRedisCacheService {
    private RedisTemplate<String, String> redisTemplate;
    private UserRedisRepository redisRepository;

    @Autowired
    public void setRedisTemplate(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Autowired
    public void setRedisRepository(UserRedisRepository redisRepository) {
        this.redisRepository = redisRepository;
    }

    @Override

    public void set(String key, User user) {
        redisRepository.save(user);
    }

    @Override
    public void delete(String username) {
        redisRepository.deleteById(username);
    }

    @Override
    public Optional<User> get(String username) {
        return redisRepository.findById(username);
    }

    @Override
    public boolean exists(String username) {
        return redisRepository.existsById(username);
    }

    @Override
    public void setField(String key, String field, String value) {
        HashOperations<String, Object, Object> opsForHash = redisTemplate.opsForHash();
        opsForHash.put(key, field, value);
    }

    @Override
    public Object getField(String key, String field) {
        HashOperations<String, Object, Object> opsForHash = redisTemplate.opsForHash();
        return opsForHash.get(key, field);
    }

    @Override
    public void deleteField(String key, String field) {
        HashOperations<String, Object, Object> opsForHash = redisTemplate.opsForHash();
        opsForHash.delete(key, field);
    }
}
